Python | 定时压缩指定文件夹发送邮件

本文介绍了一种使用Python实现的自动化工作流程,通过定时压缩指定文件夹并将压缩文件通过邮件发送。作者分享了遇到的文件路径中文问题的解决方案以及如何通过Windows定时任务来控制脚本的执行,确保在需要的时候运行。
摘要由CSDN通过智能技术生成

工作中每天需要收集部门内的FR文件,发送给外部部门的同事帮忙上传,这么发了有大半年,昨天亮光一闪,为什么不做成自动化呢,于是用python实现了整个流程,今天体验了一下真是美滋滋。

代码如下

首先导入需要的包

import win32com.client as win32
import datetime
import os
import zipfile

定义三个函数,都是网上抄别的同学作业来的(侵删)
邮箱用的是outlook

#压缩文件夹函数
def zip_ya(startdir,file_news):
    file_news = startdir +'.rar' # 压缩后文件夹的名字
    z = zipfile.ZipFile(file_news,'w',zipfile.ZIP_DEFLATED) #参数一:文件夹名
    for dirpath, dirnames, filenames in os.walk(startdir):
        fpath = dirpath.replace(startdir,'') #这一句很重要,不replace的话,就从根目录开始复制
        fpath = fpath and fpath + os.sep or ''#这句话理解我也点郁闷,实现当前文件夹以及包含的所有文件的压缩
        
实现定时压缩指定文件夹发送邮件,可以使用Python的zipfile和smtplib库。 以下是一个示例代码: ```python import zipfile import smtplib import os import time from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE from email import encoders # 定义要压缩文件夹路径和邮件相关参数 folder_to_compress = '/path/to/folder' zip_filename = 'compressed.zip' email_subject = 'Compressed Folder' email_body = 'Please find the compressed folder attached.' smtp_server = 'smtp.example.com' smtp_port = 587 smtp_username = 'example@example.com' smtp_password = 'password' sender = 'example@example.com' recipient = 'recipient@example.com' send_time = '08:00' # 压缩文件夹 def zip_folder(folder_path, output_path): with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(folder_path): for file in files: zipf.write(os.path.join(root, file)) # 发送邮件 def send_email(subject, body, attachment_path, smtp_server, smtp_port, smtp_username, smtp_password, sender, recipient): msg = MIMEMultipart() msg['From'] = sender msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(body)) with open(attachment_path, 'rb') as f: part = MIMEBase('application', 'octet-stream') part.set_payload(f.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_path)) msg.attach(part) smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.starttls() smtp.login(smtp_username, smtp_password) smtp.sendmail(sender, recipient, msg.as_string()) smtp.quit() # 定时发送邮件 while True: current_time = time.strftime('%H:%M') if current_time == send_time: zip_folder(folder_to_compress, zip_filename) send_email(email_subject, email_body, zip_filename, smtp_server, smtp_port, smtp_username, smtp_password, sender, recipient) os.remove(zip_filename) time.sleep(60) ``` 该代码会每分钟检查一次当前时间,如果与设定的发送时间一致,就压缩指定文件夹发送邮件。注意,这个代码运行时会一直循环,需要手动关闭。 请注意,这只是一个示例代码,需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值